package Services

import(
	"github.com/gin-gonic/gin"
	"fmt"
	"net/http"
	"gin/Databases"
	"gin/Common"
	"encoding/json"
	"time"
)

type TaskDetailData struct {
	Fid string `db:"Fid" json:"task_id"`
    TaskDate string `db:"Ftask_date" json:"task_date"`
    EntityName string `db:"Fentity_name" json:"entity_name"`
    StartDate string `db:"Fstart_date" json:"start_date"`
    CustomWord string `db:"Fcustom_word" json:"custom_word"`
    Url string `db:"Furl" json:"url"`
}

type TaskClassData struct {
	ClassName string `json:"class_name"`
	ClassDetail []TaskDetailData `json:"class_detail"`
}

type DisplayTaskCgi struct {
	Common.CgiBase
	TaskClassId []int
	TaskList []TaskClassData
}

func (cgi *DisplayTaskCgi)quertTaskClass() {
	sql := "select Fclass from db_custom_task where Ftask_date >=? and Fstatus in (3,4) group by(Fclass);"
	err := Databases.Db.Select(&cgi.TaskClassId, sql, cgi.Input["limit_date"])
	if err != nil {
		fmt.Println("exec failed, ", err)
		panic("query class fail")
	}
}

func (cgi *DisplayTaskCgi)quertTaskDetail() {
	for i := 0; i < len(cgi.TaskClassId); i++ {
		var c TaskClassData
		c.ClassName = Common.GetEntityClass(cgi.TaskClassId[i])
		sql := "select Fid,Ftask_date,Fentity_name,Fstart_date,Fcustom_word,Furl from db_custom_task where Ftask_date >=? and Fstatus in (2,3,4) and Fclass=? order by Fentity_name desc;"
		err := Databases.Db.Select(&c.ClassDetail, sql, cgi.Input["limit_date"], cgi.TaskClassId[i])
		if err != nil {
			fmt.Println("exec failed, ", err)
			panic("query data fail")
		}
		cgi.TaskList = append(cgi.TaskList, c)
	}
}

func (cgi *DisplayTaskCgi)transformTask() (string){
    str, _ := json.Marshal(cgi.TaskList)
    str_res := string(str)
    return str_res
}

func (cgi *DisplayTaskCgi)processParam(c *gin.Context) {
	time_now := time.Now()
	cgi.Input["limit_date"] = time_now.AddDate(0, 0, -1 * 30).Format("2006-01-02")
}

func DisplayTask(c *gin.Context) {
	defer func(){
		fmt.Println("开始处理异常")
		if err:=recover();err!=nil{
			fmt.Println("error:",err)
			c.JSON(http.StatusOK, gin.H{
		        "result": -1,
		        "msg":    err,
		        "data": "{}",
		    })
		}
	}()


	var cgi DisplayTaskCgi
	cgi.Init(c)
	cgi.processParam(c)
	cgi.quertTaskClass()
	cgi.quertTaskDetail()

	json_res := cgi.transformTask()

    c.JSON(http.StatusOK, gin.H{
        "result": 0,
        "msg":    "success",
        "data": json_res,
    })

}

